package com.admin_system.controller;

import com.admin_system.pojo.User;
import com.admin_system.service.UserService;
import com.admin_system.utils.JwtTokenUtil;
import jakarta.validation.Valid;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.Map;
import io.jsonwebtoken.ExpiredJwtException;

@RestController
public class UserController {

    private static final Logger logger = LoggerFactory.getLogger(UserController.class);

    @Autowired
    private UserService userService;
    
    @Autowired
    private JwtTokenUtil jwtTokenUtil;

    @PostMapping("/login")
    public ResponseEntity<?> login(@RequestParam String username,
                                  @RequestParam String password) {
        logger.debug("收到登录请求，账号: {}", username);
        
        // 使用通用登录方法，支持用户名或手机号登录
        User user = userService.login(username, password);

        if (user != null) {
            logger.info("用户 {} 登录成功", user.getUsername());
            logger.debug("用户信息：id={}, username={}, fullName={}, role={}", 
                    user.getId(), user.getUsername(), user.getFullName(), user.getRole());
            
            // 先使该用户的所有现有令牌失效
            userService.invalidateUserTokens(user.getUsername());
            
            // 生成JWT token
            String token = userService.generateUserToken(user);
            
            // 返回用户信息和token
            Map<String, Object> response = new HashMap<>();
            response.put("success", true);
            response.put("token", token);
            response.put("username", user.getUsername());
            response.put("fullName", user.getFullName() != null ? user.getFullName() : user.getUsername());
            response.put("role", user.getRole());
            
            return ResponseEntity.ok(response);
        } else {
            logger.warn("登录失败，账号或密码错误: {}", username);
            return ResponseEntity.status(HttpStatus.UNAUTHORIZED)
                .body(Map.of("success", false, "message", "账号或密码错误"));
        }
    }

    @PostMapping("/register")
    public ResponseEntity<?> register(@Valid @RequestBody User user) {
        logger.debug("收到注册请求，用户名: {}", user.getUsername());
        
        try {
            // 检查用户名是否已存在
            if (userService.checkUsernameExists(user.getUsername())) {
                return ResponseEntity.badRequest().body("用户名已存在");
            }
            
            // 检查手机号是否已存在
            if (userService.checkPhoneExists(user.getPhone())) {
                return ResponseEntity.badRequest().body("手机号已被注册");
            }
            
            // 注册用户
            userService.register(user);
            logger.info("用户 {} 注册成功", user.getUsername());
            return ResponseEntity.ok("注册成功");
        } catch (Exception e) {
            logger.error("用户注册失败", e);
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("注册失败：" + e.getMessage());
        }
    }
    
    /**
     * 获取当前登录用户的信息
     */
    @GetMapping("/api/user/info")
    public ResponseEntity<?> getUserInfo() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if (authentication != null && authentication.isAuthenticated()) {
            String username = authentication.getName();
            User user = userService.findByUsername(username);
            
            if (user != null) {
                // 不再生成新token，只返回用户信息
                Map<String, Object> response = new HashMap<>();
                response.put("username", user.getUsername());
                response.put("fullName", user.getFullName() != null ? user.getFullName() : user.getUsername());
                response.put("role", user.getRole());
                
                return ResponseEntity.ok(response);
            }
        }
        
        return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body("未授权");
    }
    
    /**
     * 更新当前用户的真实姓名
     * @param fullName 新的真实姓名
     * @return 更新结果
     */
    @PostMapping("/api/update-fullname")
    public ResponseEntity<?> updateFullName(@RequestParam String fullName, 
                                           @RequestHeader("Authorization") String authHeader) {
        // 从JWT Token中获取用户名
        String token = authHeader.substring(7); // 移除"Bearer "前缀
        String username;
        
        try {
            // 从token中获取用户名
            username = jwtTokenUtil.getUsernameFromToken(token);
            logger.debug("从token获取用户名: {}", username);
            
            // 查找用户
            User user = userService.findByUsername(username);
            if (user == null) {
                logger.warn("更新姓名失败：未找到用户 {}", username);
                return ResponseEntity.status(HttpStatus.NOT_FOUND)
                    .body(Map.of("success", false, "message", "未找到用户"));
            }
            
            // 更新用户真实姓名
            boolean updated = userService.updateUserFullName(user.getId(), fullName);
            
            if (updated) {
                logger.info("用户 {} 更新姓名成功: {}", username, fullName);
                
                // 返回成功响应
                Map<String, Object> response = new HashMap<>();
                response.put("success", true);
                response.put("message", "更新成功");
                response.put("fullName", fullName);
                
                return ResponseEntity.ok(response);
            } else {
                logger.warn("用户 {} 更新姓名失败", username);
                return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body(Map.of("success", false, "message", "更新失败"));
            }
        } catch (Exception e) {
            logger.error("更新真实姓名失败", e);
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                .body(Map.of("success", false, "message", "更新失败：" + e.getMessage()));
        }
    }
    
    /**
     * 仅管理员可访问的API示例
     */
    @GetMapping("/api/admin/users")
    @PreAuthorize("hasRole('ROLE_ADMIN')")
    public ResponseEntity<?> getAllUsers() {
        // 获取所有用户的逻辑...
        return ResponseEntity.ok("管理员专属API");
    }

    /**
     * 获取系统中活跃用户总数
     * 此API对所有已登录用户开放
     * 
     * @return 活跃用户总数
     */
    @GetMapping("/api/users/count")
    public ResponseEntity<?> getUserCount() {
        try {
            int userCount = userService.countActiveUsers();
            return ResponseEntity.ok(Map.of("count", userCount));
        } catch (Exception e) {
            logger.error("获取用户数量失败", e);
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                .body(Map.of("error", "获取用户数量失败：" + e.getMessage()));
        }
    }

    /**
     * 获取用户真实姓名
     * 根据用户名查询用户的真实姓名
     * 
     * @param username 用户名
     * @return 真实姓名
     */
    @GetMapping("/real-name")
    public ResponseEntity<Map<String, String>> getRealName(@RequestParam("username") String username) {
        Map<String, String> result = new HashMap<>();
        try {
            // 根据用户名查找用户
            User user = userService.findByUsername(username);
            
            // 如果找到用户并且真实姓名不为空，则返回真实姓名，否则返回用户名
            if (user != null && user.getFullName() != null && !user.getFullName().isEmpty()) {
                result.put("realName", user.getFullName());
                result.put("username", username);
            } else {
                result.put("realName", username);
                result.put("username", username);
            }
            
            return ResponseEntity.ok(result);
        } catch (Exception e) {
            logger.error("获取用户真实姓名失败", e);
            result.put("realName", username);
            result.put("username", username);
            result.put("error", e.getMessage());
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(result);
        }
    }
}